// 认证状态管理
import { authService } from '../services/authService'
import { defineStore } from 'pinia'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: JSON.parse(localStorage.getItem('cms_user') || '{}'),
    token: localStorage.getItem('cms_token') || null,
    isAuthenticated: !!localStorage.getItem('cms_token'),
  }),

  getters: {
    isLoggedIn: (state) => state.isAuthenticated,
    userInfo: (state) => state.user,
    userRole: (state) => state.user.role || 'editor',
    hasPermission: (state) => (permission) => {
      if (state.user.role === 'admin') return true
      return state.user.permissions?.includes(permission) || false
    }
  },

  actions: {
    async login(credentials) {
      try {
        const userData = await authService.login(credentials)
        // 后端返回格式: { token, username, userId, email, role, createdAt }
        this.setAuthData(userData, userData.token)
        return { success: true, user: userData }
      } catch (error) {
        return { success: false, error: error.message }
      }
    },

    logout() {
      this.user = {}
      this.token = null
      this.isAuthenticated = false
      localStorage.removeItem('cms_user')
      localStorage.removeItem('cms_token')
    },

    setAuthData(userData, authToken) {
      // 确保userData是一个新对象，触发响应式更新
      this.user = { ...userData }
      this.token = authToken
      this.isAuthenticated = true
      localStorage.setItem('cms_user', JSON.stringify(userData))
      localStorage.setItem('cms_token', authToken)
      console.log('Auth store updated:', this.user)
    },

    checkPermission(permission) {
      if (!this.user) return false
      if (this.user.role === 'admin') return true
      return this.user.permissions?.includes(permission) || false
    },

    // 初始化时验证token
    async initAuth() {
      if (this.token) {
        try {
          const userData = await authService.getCurrentUser()
          this.user = userData
        } catch (error) {
          // token无效，清除登录状态
          this.logout()
        }
      }
    }
  }
})